var express = require('express');
var router = express.Router();
var Activity = require('../models/activity.js').activity;
var qiniu = require('qiniu');
var mongoose = require('mongoose');

router.post('/', function(req, res,next) {
    var userid = req.body.userid;
    var title = req.body.title;
    var date = new Date();
    var content = req.body.content;
    var images = req.body.images;
    var money = req.body.money;
    var time = req.body.time;
    var address = req.body.address;
    var addressID = createAddressID(address);
    if (addressID) {
        var activity = new Activity({
                id: createActivityID(),
                title:(title?title:""),
                date:date,
                content:(content?content:""),
                images:(images?images:new Array()),
                money:money,
                time: time,
                address:addressID
            }
        );
        activity.save(function(err) {
            if (err) {
                res.send({
                    code:1,
                    description:'活动保存失败'
                }); // 保存失败
            } else {
                res.send({
                    code:0,
                    description:'保存成功'
                });  // 保存成功
            }
        })
    } else {
        res.send({
            code:2,
            description:'地址保存成功'
        }); // 保存address失败
    }
});

router.get('/vertify/', function(req, res) {
    if(!req.session.user) {
        res.send({
            uptoken:uptoken(''),
            code:1,
            description:'登录失败'
        });   // 登录失败
    } else {
        res.send({
                uptoken:uptoken('coco-couple-bbs'),
                code:0,
                description:'登录成功'
            }
        );   // 登录失败
    }
})

/*
* 生成活动
* */
function generateActivityID() {
    return mongoose.Schema.Types.ObjectId();
}

var Address = require('../models/activity.js').address;

/*
* 生成addressid，保存成功返回addressid，失败返回NULL
* */
function generateAddressID(address) {
    var address = new Address({
        id: mongoose.schema.Types.ObjectId,
        location: address.location,
        lat: address.gps.lat,
        lot:address.gps.lot,
        address:address.address
    });
    address.save(function(err) {
        if (err) {
            return address.id;
        } else {
            return nil;
        }
    })
}

function uptoken(bucketname) {
    var putPolicy = new qiniu.rs.PutPolicy(bucketname);
    putPolicy.callbackUrl = 'http://localhost:3000/public/';
    putPolicy.callbackBody = 'fname=$(fname)&detail=(x:detail)';
    //putPolicy.returnUrl = returnUrl;
    //putPolicy.returnBody = returnBody;
    //putPolicy.asyncOps = asyncOps;
    //putPolicy.expires = expires;
    return putPolicy.token();
}
